﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using DigitalSolutionLibrary.SqlDatabase;
using System.Diagnostics;
using DigitalSolutionLibrary.Security;
using DigitalSolutionLibrary.Utilities;
using System.IO;

namespace DigitalSolutionManagement
{
    public partial class frmEditEmployee : BaseFormEdit
    {
        private Thread th;
        private OpenMode openMode;
        private delegate void UpdateUi();
        private bool isUserUpdate;

        public override BaseFormEdit GetNewInstance(BaseFormEdit.OpenMode mode)
        {
            return new frmEditEmployee(mode);
        }

        public frmEditEmployee()
        {
        }

        public frmEditEmployee(OpenMode mode)
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            openMode = mode;
            if (mode == OpenMode.EDIT)
            {
                this.Text = formHeader1.Title = "Chỉnh sửa nhân viên";
                btnOK.Text = "Lưu";
                btnOK.Type = DigitalSolutionControls.IconButton.ButtonType.SAVE;
            }
        }

        public frmEditEmployee(OpenMode mode, int empId)
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            openMode = mode;
            if (mode == OpenMode.EDIT)
            {
                this.Text = formHeader1.Title = "Chỉnh sửa nhân viên";
                btnOK.Text = "Lưu";
                btnOK.Type = DigitalSolutionControls.IconButton.ButtonType.SAVE;
            }
            isUserUpdate = true;
            ItemId = empId;
        }

        private void PrePareForm()
        {
            //load emp type
            object obj = Program.dbWrapper.ExecuteStore("LoadEmpType", null, DatabaseWrapper.ReturnType.DATASET);
            if (obj != null)
            {
                DataSet dsEmpType = (DataSet)obj;
                cmdType.DataSource = dsEmpType.Tables[0];
                cmdType.DisplayMember = "TypeName";
                cmdType.ValueMember = "TypeId";
            }
            else
            {
                processing1.HideProcessing();
                btnOK.Enabled = false;
                MessageBox.Show("Không thể kêt nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ParameterStock stock;
            Parameter par;
            //if openmode = New, gen emp code else load emp info
            if (openMode == OpenMode.NEW)
            {
                stock = new ParameterStock();
                par = new Parameter("type", 1, SqlDbType.Int);
                stock.AddParamter(par);

                obj = Program.dbWrapper.ExecuteStore("GenerateCode", stock, DatabaseWrapper.ReturnType.FIRST_CELL);
                if (obj != null)
                {
                    txtCode.Text = obj.ToString();
                    processing1.HideProcessing();
                }
                else
                {
                    processing1.HideProcessing();
                    btnOK.Enabled = false;
                    MessageBox.Show("Không thể kêt nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {   
                stock = new ParameterStock();
                par = new Parameter("empId", ItemId, SqlDbType.Int);
                stock.AddParamter(par);

                obj = Program.dbWrapper.ExecuteStore("GetEmployee", stock, DatabaseWrapper.ReturnType.DATASET);
                if (obj != null)
                {
                    DataSet ds = (DataSet)obj;
                    txtAddr.Text = ds.Tables[0].Rows[0]["EmpAddress"].ToString();
                    if (ds.Tables[0].Rows[0]["EmpBirthday"] != DBNull.Value)
                    {
                        txtBithday.Value = (DateTime)ds.Tables[0].Rows[0]["EmpBirthday"];
                    }
                    
                    if ((bool)ds.Tables[0].Rows[0]["EmpGender"])
                        radFale.Checked = true;
                    else
                        raFemale.Checked = true;

                    txtCode.Text = ds.Tables[0].Rows[0]["EmpCode"].ToString();
                    txtEmail.Text = ds.Tables[0].Rows[0]["EmpEmail"].ToString();
                    txtName.Text = ds.Tables[0].Rows[0]["EmpName"].ToString();
                    txtPassword.Text = TripleDES.Decryption(ds.Tables[0].Rows[0]["EmpPassword"].ToString());
                    txtPhone.Text = ds.Tables[0].Rows[0]["EmpPhone"].ToString();
                    cmdType.SelectedValue = ds.Tables[0].Rows[0]["EmpType"];
                    if (ds.Tables[0].Rows[0]["EmpAvatar"] != DBNull.Value)
                    {
                        picAvatar.Image = Utility.ByteToImage((byte[])ds.Tables[0].Rows[0]["EmpAvatar"]);
                    }
                    processing1.HideProcessing();
                    if (isUserUpdate)
                        cmdType.Enabled = false;
                }
                else
                {
                    processing1.HideProcessing();
                    btnOK.Enabled = false;
                    MessageBox.Show("Không thể kêt nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void PositiveButtonClick()
        {
            Parameter param = new Parameter("code", txtCode.Text, SqlDbType.NVarChar, 50);
            ParameterStock stock = new ParameterStock();
            stock.AddParamter(param);

            param = new Parameter("password", TripleDES.Encryption(txtPassword.Text), SqlDbType.NVarChar, 100);
            stock.AddParamter(param);

            param = new Parameter("name",txtName.Text, SqlDbType.NVarChar, 50);
            stock.AddParamter(param);

            param = new Parameter("gender", radFale.Checked ? true : false, SqlDbType.Bit);
            stock.AddParamter(param);

            if (txtBithday.Value != DateTime.MinValue)
            {
                param = new Parameter("birthday", txtBithday.Value, SqlDbType.Date);
                stock.AddParamter(param);
            }

            param = new Parameter("address", txtAddr.Text, SqlDbType.NVarChar, 100);
            stock.AddParamter(param);

            param = new Parameter("email", txtEmail.Text, SqlDbType.NVarChar, 100);
            stock.AddParamter(param);

            param = new Parameter("phone", txtPhone.Text, SqlDbType.NVarChar, 50);
            stock.AddParamter(param);

            if (picAvatar.Image != null)
            {
                param = new Parameter("avatar", Utility.ImageToByte(picAvatar.Image), SqlDbType.Image);
                stock.AddParamter(param);
            }

            param = new Parameter("type", cmdType.SelectedValue, SqlDbType.Int);
            stock.AddParamter(param);

            param = new Parameter("message", null, SqlDbType.NVarChar, ParameterDirection.Output, 200);
            stock.AddParamter(param);

            param = new Parameter("id", ItemId, SqlDbType.Int);
            stock.AddParamter(param);

            object obj = Program.dbWrapper.ExecuteStore(openMode == OpenMode.NEW ? "AddEmployee" : "EditEmployee", stock, DatabaseWrapper.ReturnType.FIRST_CELL);
            if (obj == null)
            {
                processing1.HideProcessing();
                MessageBox.Show("Không thể kết nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                int code = (int)obj;
                if (code > 0)
                {
                    if (isUserUpdate)
                    {
                        RefreshList("frmWelcome");
                        DialogResult = DialogResult.Cancel;
                    }
                    else
                        DialogResult = DialogResult.OK;
                }
                else if (code == 0)//Duplicate emp code->gen new code
                {
                    stock = new ParameterStock();
                    param = new Parameter("type", 1, SqlDbType.Int);
                    stock.AddParamter(param);

                    obj = Program.dbWrapper.ExecuteStore("GenerateCode", stock, DatabaseWrapper.ReturnType.FIRST_CELL);
                    if (obj != null)
                    {
                        txtCode.Text = obj.ToString();
                        processing1.HideProcessing();
                        MessageBox.Show(stock.GetByName("message").ValueOut.ToString(), "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        processing1.HideProcessing();
                        btnOK.Enabled = false;
                        MessageBox.Show("Không thể kêt nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    processing1.HideProcessing();
                    MessageBox.Show(stock.GetByName("message").ValueOut.ToString(), "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void frmEditEmployee_Load(object sender, EventArgs e)
        {
            formHeader1.Title = this.Text;
            processing1.ShowProcessing();
            th = new Thread(() => PrePareForm());
            th.Start();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void frmEditEmployee_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (th != null && th.IsAlive)
                th.Abort();
        }

        private void picAvatar_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FileInfo finfo = new FileInfo(openFileDialog1.FileName);
                if (finfo.Length > 1024 * 100)
                {
                    MessageBox.Show("Dung lượng ảnh quá lớn, vui lòng chọn ảnh nhỏ hơn 100KB", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    picAvatar.BackgroundImage = null;
                    picAvatar.ImageLocation = openFileDialog1.FileName;
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtName.Text == String.Empty)
            {
                MessageBox.Show("Vui lòng nhập tên nhân viên", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtName.Focus();
                return;
            }
            if (txtEmail.Text != String.Empty && !txtEmail.IsValidEmail())
            {
                MessageBox.Show("Địa chỉ email không đúng", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmail.Focus();
                return;
            }
            if (txtPhone.Text != String.Empty && !txtPhone.IsValidPhone())
            {
                MessageBox.Show("Số điện thoại không đúng", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPhone.Focus();
                return;
            }
            if (!txtBithday.Empty && !txtBithday.IsValidDate())
            {
                MessageBox.Show("Năm sinh không đúng", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBithday.Focus();
                return;
            }
            if (txtPassword.Text == String.Empty)
            {
                MessageBox.Show("Vui lòng nhập mật khẩu", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return;
            }

            processing1.ShowProcessing();
            th = new Thread(() => PositiveButtonClick());
            th.Start();
        }

        private void lblClear_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (picAvatar.Image!=null)
            {
                picAvatar.Image = null;
                picAvatar.BackgroundImage = Properties.Resources.no_image;
            }
        }
    }
}
